'use client';

import { useEffect, useState } from 'react';
import { Table, Button, Card, Typography, Message, Spin, Badge, Space, Modal, Form, Input, Select, InputNumber } from '@arco-design/web-react';
import { IconPlus, IconEdit, IconDelete } from '@arco-design/web-react/icon';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import { roomApi } from '@/services/api';
import { Room } from '@/types';

const { Title } = Typography;
const FormItem = Form.Item;
const Option = Select.Option;

export default function AdminRoomsPage() {
  const [rooms, setRooms] = useState<Room[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加房间');
  const [modalLoading, setModalLoading] = useState(false);
  const [editingRoom, setEditingRoom] = useState<Room | null>(null);
  const [form] = Form.useForm();

  const { userType, isAuthenticated } = useAuth();
  const router = useRouter();

  useEffect(() => {
    // 如果未登录或不是管理员，重定向到登录页
    if (!isAuthenticated) {
      router.push('/admin/login');
      return;
    }

    if (userType !== 'admin') {
      router.push('/');
      return;
    }

    fetchRooms();
  }, [isAuthenticated, userType, router]);

  const fetchRooms = async () => {
    setLoading(true);
    try {
      const response = await roomApi.getAll();
      console.log('获取房间列表响应:', response);

      if (response.code === 200 && response.data) {
        console.log('房间列表数据:', response.data);
        setRooms(response.data);
      } else {
        console.error('获取房间列表失败:', response);
        // Message.error(response.message || '获取房间列表失败');
      }
    } catch (error) {
      console.error('获取房间列表错误:', error);
      // Message.error('获取房间列表时发生错误');
    } finally {
      setLoading(false);
    }
  };

  const showAddModal = () => {
    setModalTitle('添加房间');
    setEditingRoom(null);
    form.resetFields();
    setModalVisible(true);
  };

  const showEditModal = (room: Room) => {
    setModalTitle('编辑房间');
    setEditingRoom(room);
    form.setFieldsValue({
      roomNumber: room.roomNumber,
      roomType: room.roomType,
      status: room.status,
      price: room.price,
    });
    setModalVisible(true);
  };

  const handleModalOk = async () => {
    try {
      await form.validate();
      const values = form.getFieldsValue();
      console.log('表单原始值:', values);

      // 确保状态值正确且去除可能的空格
      const statusValues = ['空闲', '预订', '占用', '清洁中'];
      const trimmedStatus = values.status.trim();
      console.log('处理后的状态值:', trimmedStatus);
      console.log('状态值是否有效:', statusValues.includes(trimmedStatus));

      if (!statusValues.includes(trimmedStatus)) {
        // Message.error('无效的房间状态');
        return;
      }

      // 使用处理后的值
      const processedValues = {
        ...values,
        status: trimmedStatus,
        roomNumber: values.roomNumber.trim(),
        roomType: values.roomType.trim()
      };

      console.log('处理后的完整值:', processedValues);

      setModalLoading(true);

      if (editingRoom) {
        // 更新房间
        console.log('更新房间，ID:', editingRoom.roomId);
        const response = await roomApi.update(editingRoom.roomId!, processedValues);
        console.log('更新响应:', response);
        if (response.code === 200) {
          Message.success('房间更新成功');
          fetchRooms();
          setModalVisible(false);
        } else {
          // Message.error(response.message || '更新房间失败');
        }
      } else {
        // 添加房间
        console.log('添加新房间');
        const response = await roomApi.create(processedValues as Omit<Room, 'roomId'>);
        console.log('添加响应:', response);
        if (response.code === 200) {
          Message.success('房间添加成功');
          fetchRooms();
          setModalVisible(false);
        } else {
          // Message.error(response.message || '添加房间失败');
        }
      }
    } catch (error) {
      console.error('表单验证错误:', error);
    } finally {
      setModalLoading(false);
    }
  };

  const handleDelete = (roomId: number) => {
    Modal.confirm({
      title: '删除房间',
      content: '确定要删除这个房间吗？此操作不可撤销。',
      okButtonProps: {
        status: 'danger',
      },
      onOk: async () => {
        try {
          const response = await roomApi.delete(roomId);
          if (response.code === 200) {
            Message.success('房间已删除');
            fetchRooms(); // 刷新列表
          } else {
            // Message.error(response.message || '删除房间失败');
          }
        } catch (error) {
          console.error('删除房间错误:', error);
          // Message.error('删除房间时发生错误');
        }
      },
    });
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case '空闲':
        return <Badge status="success" text="空闲" />;
      case '预订':
        return <Badge status="processing" text="预订" />;
      case '占用':
        return <Badge status="warning" text="占用" />;
      case '清洁中':
        return <Badge status="default" text="清洁中" />;
      default:
        return <Badge status="default" text={status} />;
    }
  };

  const columns = [
    {
      title: '房间ID',
      dataIndex: 'roomId',
      width: 80,
    },
    {
      title: '房间号',
      dataIndex: 'roomNumber',
      width: 100,
    },
    {
      title: '房间类型',
      dataIndex: 'roomType',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (status: string) => getStatusBadge(status),
    },
    {
      title: '价格/晚',
      dataIndex: 'price',
      width: 100,
      render: (price: number) => `¥${price}`,
    },
    {
      title: '操作',
      width: 160,
      render: (_: any, record: Room) => (
        <Space>
          <Button
            type="text"
            icon={<IconEdit />}
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="text"
            status="danger"
            icon={<IconDelete />}
            onClick={() => handleDelete(record.roomId!)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="py-6">
      <Card className="shadow-sm">
        <div className="flex justify-between items-center mb-6">
          <Title heading={3}>房间管理</Title>
          <Button
            type="primary"
            icon={<IconPlus />}
            onClick={showAddModal}
          >
            添加房间
          </Button>
        </div>

        {loading ? (
          <div className="flex justify-center py-12">
            <Spin />
          </div>
        ) : (
          <Table
            columns={columns}
            data={rooms}
            loading={loading}
            pagination={{
              pageSize: 10,
              showTotal: true,
            }}
            rowKey="roomId"
            borderCell={true}
          />
        )}
      </Card>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        confirmLoading={modalLoading}
        maskClosable={false}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <FormItem
            label="房间号"
            field="roomNumber"
            rules={[{ required: true, message: '请输入房间号' }]}
          >
            <Input placeholder="请输入房间号" />
          </FormItem>

          <FormItem
            label="房间类型"
            field="roomType"
            rules={[{ required: true, message: '请选择房间类型' }]}
          >
            <Select placeholder="请选择房间类型">
              <Option value="标准间">标准间</Option>
              <Option value="大床房">大床房</Option>
              <Option value="豪华套房">豪华套房</Option>
              <Option value="家庭房">家庭房</Option>
            </Select>
          </FormItem>

          <FormItem
            label="状态"
            field="status"
            rules={[{ required: true, message: '请选择房间状态' }]}
          >
            <Select placeholder="请选择房间状态">
              <Option value="空闲">空闲</Option>
              <Option value="预订">预订</Option>
              <Option value="占用">占用</Option>
              <Option value="清洁中">清洁中</Option>
            </Select>
          </FormItem>

          <FormItem
            label="价格/晚"
            field="price"
            rules={[{ required: true, message: '请输入房间价格' }]}
          >
            <InputNumber
              placeholder="请输入房间价格"
              prefix="¥"
              min={0}
              precision={2}
              step={10}
            />
          </FormItem>
        </Form>
      </Modal>
    </div>
  );
}